package com.baizhi.controller;

import com.baizhi.entity.Picture;
import com.baizhi.entity.Result;
import com.baizhi.service.PictureService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;

@RequestMapping("picture")
@Controller
public class PictureController {

    @Autowired
    private PictureService pictureService;

    @RequestMapping("findById")
    @ResponseBody
    public List<Picture> findById(String id){
        return  pictureService.findById(id);
    }

    @RequestMapping("save")
    @ResponseBody
    public Result save(String productId, MultipartFile[] multipartFile, HttpServletRequest request){
        Result result = null;
        try{
            String realPath = request.getSession().getServletContext().getRealPath("/back/image/picture");
            Picture picture = new Picture();
            for (MultipartFile file : multipartFile) {
                String uuid = UUID.randomUUID().toString();
                String urlname = uuid+"."+FilenameUtils.getExtension(file.getOriginalFilename());
                String path = "/back/image/picture/"+urlname;
                picture.setId(uuid);
                picture.setProductid(productId);
                picture.setPath(path);
                pictureService.save(picture);
                file.transferTo(new File(realPath,urlname));
            }
        }catch (Exception e){
            e.printStackTrace();
            result = new Result();
            result.setMessage("添加失败");
        }
        return result;
    }

    @RequestMapping("delete")
    @ResponseBody
    public Result delete(String id,HttpServletRequest request){
        Result result = null;
        try{
            Picture byPrimaryId = pictureService.findByPrimaryId(id);
            String realPath = request.getSession().getServletContext().getRealPath(byPrimaryId.getPath());
            File file = new File(realPath);
            file.delete();
            pictureService.delete(id);
        }catch (Exception e){
            e.printStackTrace();
            result = new Result();
            result.setMessage("删除失败");
        }
        return result;
    }
}
